using System.Buffers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Logging;

namespace Server
{
    public class MyEchoConnectionHandler : ConnectionHandler
    {
        private readonly ILogger<MyEchoConnectionHandler> _logger;

        public MyEchoConnectionHandler(ILogger<MyEchoConnectionHandler> logger)
        {
            _logger = logger;
        }

        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            var input = connection.Transport.Input;
            _logger.LogInformation(connection.ConnectionId + " connected");
            try
            {
                while (true)
                {
                    var result = await input.ReadAsync();
                    var buffer = result.Buffer;

                    ProcessMessage(ref buffer);

                    input.AdvanceTo(buffer.Start, buffer.End);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }
            finally
            {
                _logger.LogInformation(connection.ConnectionId + " disconnected");
            }

            void ProcessMessage(ref ReadOnlySequence<byte> buffer)
            {
                while (true)
                {
                    SequencePosition? position = buffer.PositionOf((byte)'\n');
                    if (position == null) break;
                    var line = buffer.Slice(0, position.Value);
                    string msg = Encoding.UTF8.GetString(line);
                    Console.WriteLine(msg+DateTime.Now.ToString("HH:mm:ss.fff"));

                    buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
                }
            }

        }
    }
}